package org.tuestudent.grouppa;

import java.util.ArrayList;
import java.util.HashMap;

import org.tuestudent.grouppa.AppContext.ActiveScreens;
import org.tuestudent.grouppa.GroupViewController.CreateGroupResponse;
import org.tuestudent.grouppa.GroupViewController.JoinGroupResponse;
import org.tuestudent.grouppa.ViewController.notificationIds;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Fragment;
import android.app.FragmentTransaction;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;

public class GrouppaScreen extends Activity implements OnItemClickListener,
        OnTouchListener {

    // Title of the drawer(menu)
    private CharSequence drawerTitle;
    private CharSequence title;

    // Name of the menu items
    private String[] drawerTiles;

    // ListView containing the menu items
    private ListView drawerList;

    // Drawer(menu)
    private DrawerLayout drawerLayout;

    // ActionBar drawer toggle
    private ActionBarDrawerToggle drawerToggle;

    ProgressDialog currentProgressDialog = null;
    AlertDialog currentAlertDialog = null;

    // The current fragment visible
    private String visibleFrag="";

    public void turnOffDialogs() {
        if (currentProgressDialog != null && currentProgressDialog.isShowing()) {

            currentProgressDialog.dismiss();
        }
        if (currentAlertDialog != null && currentAlertDialog.isShowing()) {
            currentAlertDialog.dismiss();
        }
    }

    /**
     * shows an error message
     * 
     * @param errorMessage
     *            text to show inside error message
     */
    public void errorPopup(String errorMessage) {
        turnOffDialogs();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(errorMessage);
        builder.setTitle("Error");
        android.content.DialogInterface.OnClickListener closer =
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        turnOffDialogs();

                    }
                };
        builder.setPositiveButton("OK", closer);
        currentAlertDialog = builder.create();
        currentAlertDialog.show();
    }

    /**
     * shows an connection error message with ability to cancel reconnection
     * 
     * @param errorMessage
     *            text to show inside error message
     */
    public void connectionErrorPopup(String errorMessage) {
        turnOffDialogs();
        android.content.DialogInterface.OnClickListener closer =
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        turnOffDialogs();
                        Main.getConnection().retry = false;
                        
                    }
                };

        currentProgressDialog = new ProgressDialog(this);
        currentProgressDialog.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel", closer);
        currentProgressDialog.setTitle("Connection error");
        currentProgressDialog.setMessage(errorMessage);
        currentProgressDialog.show();
    }
    
    /**
     * show a message with information about some action succeeding
     * 
     * @param text
     *            text to display
     */
    public void actionSuccess(String text) {
        turnOffDialogs();
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(text);
        builder.setTitle("Success!");
        android.content.DialogInterface.OnClickListener closer =
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        turnOffDialogs();

                    }
                };
        builder.setPositiveButton("OK", closer);
        currentAlertDialog = builder.create();
        currentAlertDialog.show();

    }

    /**
     * shows a message that application is waiting for something (for example
     * for server response)
     * 
     * @param text
     *            text to show
     */
    public void busyMessage(String text) {
        turnOffDialogs();
        currentProgressDialog = ProgressDialog.show(this, "", text, true);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.grouppa_screen);

        // get Title of the drawer
        title = drawerTitle = getTitle();

        // get the content of the drawer from a resource list
        drawerTiles = getResources().getStringArray(R.array.drawer_list);

        // select the ListView for the drawer items
        drawerList = (ListView) findViewById(R.id.drawer);

        // select the DrawerLayout for the ListView with drawer items
        drawerLayout = (DrawerLayout) findViewById(R.id.container);

        // Insertion of the drawer items in the ListView
        drawerList.setAdapter(new ArrayAdapter<String>(this,
                R.layout.drawer_list_item, drawerTiles));
        // OnClickListener to the drawer
        drawerList.setOnItemClickListener(this);

        // enable ActionBar app icon to behave as action to toggle nav drawer
        getActionBar().setDisplayHomeAsUpEnabled(true);
        getActionBar().setHomeButtonEnabled(true);

        drawerToggle =
                new ActionBarDrawerToggle(this, drawerLayout,
                        R.drawable.ic_drawer, R.string.drawer_open,
                        R.string.drawer_close) {

                    public void onDrawerClosed(View view) {
                        getActionBar().setTitle(title);
                        invalidateOptionsMenu(); // creates call to
                                                 // onPrepareOptionsMenu()
                    }

                    public void onDrawerOpened(View drawerView) {
                        getActionBar().setTitle("Menu");
                        invalidateOptionsMenu(); // creates call to
                                                 // onPrepareOptionsMenu()
                    }
                };

        drawerLayout.setDrawerListener(drawerToggle);

        // method to visualize the correct fragment
        if (savedInstanceState == null) {
            // visibleFrag set to myGroups
            visibleFrag = "myGroups";

            FragmentTransaction manager =
                    getFragmentManager().beginTransaction();
            // add the created fragment to fragment_container
            manager.add(R.id.fragment_container, new MyGroups(), visibleFrag);
            // enable back button action
            manager.addToBackStack(null);
            // commit the transaction
            manager.commit();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Change the menu based on the current fragment.
        // This will be done when onCreate has the setHasOptionMenu(true)
        // in the fragment
        if (visibleFrag.equals("myGroups")) {
            getMenuInflater().inflate(R.menu.my_groups, menu);
            return true;
        } else if (visibleFrag.equals("groupInfo")) {
            getMenuInflater().inflate(R.menu.group_info, menu);
            return true;
        } else if (visibleFrag.equals("chat")) {
            getMenuInflater().inflate(R.menu.chat, menu);
            return true;
        } else if (visibleFrag.equals("wall")) {
            getMenuInflater().inflate(R.menu.wall, menu);
            return true;
        } else if (visibleFrag.equals("tasks")) {
            getMenuInflater().inflate(R.menu.tasks, menu);
            return true;
        } else if (visibleFrag.equals("viewTopic")) {
            getMenuInflater().inflate(R.menu.view_topic, menu);
            return true;
        } else {
            return super.onCreateOptionsMenu(menu);
        }
    }

    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        // The action bar home/up action should open or close the drawer.
        if (drawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        // The action to be taken when one of the options is clicked.
        int id = item.getItemId();
            
//        Buttons in the menu removed
//        if (id == R.id.option_edit_group) {
//            return true;
//        } else if (id == R.id.option_leave_group) {
//            return true;
//        } else 
        if (id == R.id.option_my_profile) {
            UserProfile userProfile = new UserProfile();
            userProfile.show(getFragmentManager(), "userProfile");
            /*
             * AlertDialog.Builder builder = new AlertDialog.Builder(this); //
             * Get the layout inflater LayoutInflater inflater =
             * this.getLayoutInflater(); // Inflate and set the layout for the
             * dialog // Pass null as the parent view because its going in the
             * dialog layout
             * builder.setView(inflater.inflate(R.layout.popup_profile, null));
             * final AlertDialog profile = builder.create(); profile.show();
             * EditText nickname = (EditText)
             * profile.findViewById(R.id.nickname);
             */
            return true;
        } else if (id == R.id.option_sign_out) {
            finish();
            return true;
        } else {
            return super.onOptionsItemSelected(item);
        }

    }

    // Item clicked in the drawer
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
        // method to execute fragment visualization
        selectFragment(position);
    }

    // method that selects the right fragment to be visualized
    public void selectFragment(int pos) {

        // basic fragment not used
        hideSoftKeyboard(GrouppaScreen.this);
        String group = Main.getContext().getCurrentGroup();
        if (group == null || group.isEmpty()) {
            Main.getContext().grouppaActivity
                    .errorPopup("You should select your group first");
            return;
        }
        Fragment showFragment = new Fragment();
        // Tag for the visible fragment
        visibleFrag = "";

        // Use case distinctions to visualize the right fragment
        switch (pos) {
        // My groups fragment
        case 0:
            showFragment = new MyGroups();
            visibleFrag = "myGroups";
            break;

        // Group info fragment
        case 1:
            showFragment = new GroupInfo();
            visibleFrag = "groupInfo";
            break;

        // Chat fragment
        case 2:
            showFragment = new Chat();
            visibleFrag = "chat";
            break;

        // Wall fragment
        case 3:
            showFragment = new Wall();
            visibleFrag = "wall";
            break;

        // Tasks fragment
        case 4:
            showFragment = new Tasks();
            visibleFrag = "tasks";
            break;
        }

        // Fragment manager controlling the transaction
        getFragmentManager().beginTransaction()
        // replace the created fragment to fragment_container
                .replace(R.id.fragment_container, showFragment, visibleFrag)
                // enable back button action
                // .addToBackStack(null)
                // commit the transaction
                .commit();

        // show the selected item of the drawer
        drawerList.setItemChecked(pos, true);
        // set the title
        if (pos < 5) {
            title = drawerTiles[pos];
        } else {
            title = "Topic";
        }
        // set the title to be equal to the fragment title
        getActionBar().setTitle(title);
        // close the drawer after selection
        drawerLayout.closeDrawer(drawerList);

    }

    private PeriodicUpdater updater = null;

    @Override
    protected void onStart() {
        super.onStart();
        AppContext ctx = Main.getContext();
        ctx.activeScreen = ActiveScreens.grouppaScreen;
        ctx.grouppaActivity = this;
        updater = Main.getUpdater();
        if(updater != null)
        {
            updater.stop();
        }
        updater = new PeriodicUpdater(4000);
        Main.setUpdater(updater);
        (new Thread(updater)).start();
        
        switchIntent(getIntent());
    }

    /**
     * in case this screen was turned on by a notification
     * this method must direct the user to a proper subscreen (fragment)
     */
    private void switchIntent(Intent intent) {
        if(intent.hasExtra("notificationId"))
        { 
            notificationIds notificationId = notificationIds.values()[intent.getIntExtra("notificationId", -1)];
            AppContext ctx = Main.getContext();
            ctx.currentAccessToken = intent.getStringExtra("accessToken");
            ctx.currentUserName = intent.getStringExtra("userName");
            ctx.currentUserPassword = intent.getStringExtra("userPass");
            try {
                ctx.setCurrentGroup(intent.getStringExtra("group"),false);
            } catch (Exception e) {
                e.printStackTrace();
            }

            switch(notificationId)
            {
            case chatMessageNotification:
                selectFragment(2);
                break;
            case forumMessageNotification:
                selectFragment(3);
                break;
                
            }
        }
        intent.removeExtra("notificationId");
    }

    public void onCreateGroupResponse(CreateGroupResponse response) {
        if ( !response.created || !response.joined) {
            errorPopup(response.errorReason);
        } else {
            if ( !response.manager) {
                actionSuccess("Group was created, but you are not its manager.");
            } else {
                actionSuccess("Group created, you are now its manager.");
            }
        }

    }

    /**
     * Function to create and show popup form specified id
     * 
     * @param layoutId
     *            id of the popup to show
     * @return reference to the popup
     */
    public AlertDialog showPopUp(int layoutId) {
        AlertDialog newPopup;
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        // Get the layout inflater
        LayoutInflater inflater = this.getLayoutInflater();

        // Inflate and set the layout for the dialog
        // Pass null as the parent view because its going in the dialog layout
        builder.setView(inflater.inflate(layoutId, null));
        // create the popup
        newPopup = builder.create();
        newPopup.show();
        return newPopup;
    }

    @Override
    // method that hides the keyboard when pressed outside the
            public
            boolean onTouchEvent(MotionEvent event) {

        hideSoftKeyboard(GrouppaScreen.this);

        return false;
    }

    /**
     * Method to hide the keyboard in the current fragment
     * 
     * @param activity
     */
    public static void hideSoftKeyboard(Activity activity) {
        try {
            InputMethodManager im =
                    (InputMethodManager) activity
                            .getSystemService(Activity.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(activity.getCurrentFocus()
                    .getWindowToken(), 0);
        } catch (Exception e) {

        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        hideSoftKeyboard(GrouppaScreen.this);
        return false;
    }

    @Override
    protected void onStop() {
        super.onStop();
        if (updater != null) {
            updater.stop();
            updater = null;
        }
    }

}
